<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="员工姓名" prop="nickname">
            <ns-input v-model="formData.nickname" placeholder="请输入员工姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号码" prop="mobile">
            <ns-input v-model="formData.mobile" maxlength="11" placeholder="请输入手机号码" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="归属机构" prop="deptId">
            <el-cascader
              v-model="formData.deptId"
              clearable
              placeholder="请选择归属机构"
              :props="cascaderProps"
              :options="deptList"
              filterable
              class="!w-240px"
              value-on-clear=""
              :filter-method="sysFilterMethod"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="归属系统" prop="sysId">
            <el-cascader
              v-model="formData.sysId"
              placeholder="请选择归属系统"
              class="!w-240px"
              :props="systemCascaderProps"
              :options="systemList"
              filterable
              value-on-clear=""
              clearable
              :filter-method="sysFilterMethod"
          /></el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item v-if="formData.id === undefined" label="员工编号" prop="username">
            <ns-input
              v-model="formData.username"
              placeholder="请输入员工编号"
              @input="formData.username = formData.username.replace(/[\u4e00-\u9fa5]/gi, '')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            v-if="formData.id === undefined"
            label="用户密码"
            prop="password"
            :inline-message="true"
          >
            <ns-input
              v-model="formData.password"
              placeholder="请输入用户密码"
              show-password
              type="password"
              @input="formData.password = formData.password.replace(/[\u4e00-\u9fa5]/gi, '')"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户性别">
            <el-select v-model="formData.sex" placeholder="请选择">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_USER_SEX)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="岗位" prop="postIds">
            <el-select v-model="formData.postIds" multiple placeholder="请选择">
              <el-option
                v-for="item in postList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item label="用户类型" prop="type">
            <el-select v-model="formData.type" placeholder="请选择">
              <el-option label="管理员用户" value="管理员用户" />
              <el-option label="普通用户" value="普通用户" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <ns-input v-model="formData.email" maxlength="50" placeholder="请输入邮箱" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注">
            <ns-input
              v-model="formData.remark"
              placeholder="请输入内容"
              type="textarea"
              @input="handleInput"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { sysFilterMethod } from '@/utils/selectFilter'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { CommonStatusEnum } from '@/utils/constants'
import { getSimpleSystemList } from '@/api/asset/taskManage'
import { defaultProps, handleTree } from '@/utils/tree'
import * as PostApi from '@/api/system/post'
import * as DeptApi from '@/api/system/dept'
import * as UserApi from '@/api/system/user'
import * as ConfigApi from '@/api/system/config'

defineOptions({ name: 'SystemUserForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const passwordRule = ref()
const formData = ref({
  nickname: '',
  deptId: '',
  sysId: '',
  mobile: '',
  email: '',
  id: undefined,
  username: '',
  password: '',
  sex: undefined,
  postIds: [],
  remark: '',
  type: '',
  status: CommonStatusEnum.ENABLE,
  roleIds: []
})
// 默认密码校验
const validatePassword = (rule: any, value: any, callback: any) => {
  // 构建正则表达式，根据校验规则生成对应的正则模式
  let pattern = '^'
  if (passwordRule.value?.includeDigits) pattern += '(?=.*[0-9])' // 包含数字
  if (passwordRule.value?.includeLetters) pattern += '(?=.*[a-zA-Z])' // 包含字母
  if (passwordRule.value?.includeSpecialChars) pattern += '(?=.*[!@#$%^&+=])' // 包含特殊字符，你也可以根据具体需要调整特殊字符的范围
  pattern += `.{${passwordRule.value?.length},}$` // 最小长度

  // 创建正则表达式对象
  const regex = new RegExp(pattern)
  // 进行校验
  if (!value) {
    callback()
  } else if (!regex.test(value)) {
    const digits = passwordRule.value?.includeDigits ? '数字，' : ''
    const letters = passwordRule.value?.includeLetters ? '字母，' : ''
    const specialChars = passwordRule.value?.includeSpecialChars ? '特殊字符（!@#$%^&*），' : ''
    const lengthLimit = passwordRule.value?.length ? `最小长度为${passwordRule.value.length}` : ''
    const needAnd = (digits || letters || specialChars) && lengthLimit ? '以及' : ''
    const warning = `必须含${digits + letters + specialChars + needAnd + lengthLimit}`
    callback(new Error(warning))
  } else {
    callback()
  }
}
const isRequired = computed(() => {
  return !formData.value.deptId && !formData.value.sysId
})

const formRules = computed(() => ({
  deptId: [{ required: isRequired.value, message: '归属机构不能为空', trigger: 'change' }],
  sysId: [{ required: isRequired.value, message: '归属系统不能为空', trigger: 'change' }],
  username: [{ required: true, message: '员工编号不能为空', trigger: 'blur' }],
  nickname: [{ required: true, message: '用户姓名不能为空', trigger: 'blur' }],
  password: [{ validator: validatePassword, trigger: 'blur' }],
  // type: [{ required: true, message: '用户类型不能为空', trigger: 'blur' }],
  // postIds: [{ required: true, message: '岗位不能为空', trigger: 'change' }],
  email: [
    {
      type: 'email',
      message: '请输入正确的邮箱地址',
      trigger: ['blur', 'change']
    }
  ],
  mobile: [
    {
      pattern: /^(?:(?:\+|00)86)?1(?:3[\d]|4[5-79]|5[0-35-9]|6[5-7]|7[0-8]|8[\d]|9[189])\d{8}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ]
}))
const formRef = ref() // 表单 Ref
const deptList = ref<Tree[]>([]) // 树形结构
const postList = ref([]) // 岗位列表
const systemCascaderProps = {
  checkStrictly: true,
  label: 'value',
  value: 'id',
  children: 'children',
  emitPath: false
}
const cascaderProps = {
  checkStrictly: true,
  label: 'name',
  value: 'id',
  children: 'children',
  emitPath: false
}

function handleInput(value) {
  // 先替换空格
  let newValue = value.replace(/\s+/g, '')
  // 检查长度，如果超出500字符则截断
  if (newValue.length > 500) {
    newValue = newValue.substring(0, 500)
  }
  // 更新数据
  formData.value.remark = newValue
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  getConfig()
  getSystemList()
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await UserApi.getUser(id)
      formData.value.sex = formData.value.sex === 0 ? '' : formData.value.sex
      formData.value.sysName = undefined
      formData.value.deptName = undefined
      formData.value.deptId = formData.value.deptId == '0' ? '' : formData.value.deptId
    } finally {
      formLoading.value = false
    }
  }
  // 加载部门树
  deptList.value = await DeptApi.getSimpleDeptList()
  // 加载岗位列表
  postList.value = await PostApi.getSimplePostList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as UserApi.UserVO
    data.sysId = data.sysId || ''
    data.deptId = data.deptId == '' ? '0' : data.deptId

    if (formType.value === 'create') {
      await UserApi.createUser(data)
      message.success(t('common.createSuccess'))
    } else {
      await UserApi.updateUser(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

// 获取系统配置
const getConfig = async () => {
  const data = await ConfigApi.clientGet()
  const complexities = data.passwordComplexity.split(',').map(Number)
  passwordRule.value = {
    includeDigits: complexities.indexOf(1) !== -1,
    includeLetters: complexities.indexOf(2) !== -1,
    includeSpecialChars: complexities.indexOf(3) !== -1,
    length: data.minLength
  }
}

const systemList = ref()
const getSystemList = async () => {
  const data = await getSimpleSystemList({})
  systemList.value = handleTree(data, 'id', 'pid')
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    nickname: '',
    deptId: '',
    sysId: '',
    mobile: '',
    email: '',
    id: undefined,
    username: '',
    password: '',
    sex: undefined,
    postIds: [],
    remark: '',
    type: '',
    status: CommonStatusEnum.ENABLE,
    roleIds: []
  }
  formRef.value?.resetFields()
}
</script>
